local json = require "cjson"
local G = {}
local common = require "resty.common"
local debug = common.hi_log
local aes_fucn = require "aes_en_de"
local uci = require "uci"
uci = uci.cursor()
local NGX_ERR = false

local host_url = uci:get("hiswi", "device_info", "hostname")


function G.http_ping(host, port)
    local httpc = require("resty.http").new()
    httpc:set_timeout(5000)
    local ok, err = httpc:connect(host, port, "")
    httpc:close()
    if not ok then
        return false
    end
    return true
end

function G.http_request(url, body)
    local httpc = require("resty.http").new()
    local res, err = httpc:request_uri(url, {
        method = "POST",
        keepalive = 10,
        ssl_verify = false,
        body = ngx.encode_base64(body),
        headers = {
            ["Content-Type"] = "application/x-www-form-urlencoded",
        },
    })
    httpc:close();

    if not res then
        debug("http_request error: " .. err)
        ngx.exit(200)
    end

    if res.status ~= 200 and res.status ~= 204 then
        debug("http: request error: " .. url .. res.status)
        return false
    end

    res.body = string.gsub(res.body, "\r\n", "")
    res.body = string.gsub(res.body, "%s+", "")
    local ret = ngx.decode_base64(res.body)

    -- 匹配对应的 uri
    local m, err = ngx.re.match(url, [[https?://[^/]+(:\d+)?(/[^?]*)]], "jo")
    if not m then
        debug("http uri match failure")
    end
    if m[2] == '/cgi-bin/ap/chatgpt.lua'
        or m[2] == '/cgi-bin/ap/dev_register.lua'
    then
        ret = aes_fucn.aes_cbc_128_decrypt(ret)
    end
    --判断 ret 是否未空对象
    if ret == "{}" or ret == nil then
        debug("ret null")
        return NGX_ERR
    end
    ret = json.decode(ret)
    return ret
end

function G.http_request2(url, body)
    local client_cookie = ngx.req.get_headers()["Cookie"]
    local httpc = require("resty.http").new()
    local res, err = httpc:request_uri(url, {
        method = "POST",
        keepalive = 10,
        ssl_verify = false,
        body = body,
        headers = {
            ["Content-Type"] = "application/x-www-form-urlencoded",
            ["Cookie"] = client_cookie
        },
    })
    httpc:close();

    if not res then
        debug("http_request error: " .. err)
        ngx.exit(200)
    end

    if res.status ~= 200 and res.status ~= 204 then
        debug("http: request error: " .. url .. res.status)
        return false
    end

    return json.decode(res.body)
end

function G.http_request_draw(url, body, method)
    local httpc = require("resty.http").new()
    local res, err = nil, nil
    if method == 'POST' then
        res, err = httpc:request_uri(url, {
            method = method,
            body = body or {},
            headers = {
                ["Content-Type"] = "application/json",
            },
        })
    else
        res, err = httpc:request_uri(url, {
            method = method,
        })
    end
    httpc:close();

    if not res then
        debug("http_request error: " .. err)
        ngx.exit(200)
    end

    if res.status ~= 200 and res.status ~= 204 then
        debug("http: request error: " .. url .. res.status)
        return false
    end

    return json.decode(res.body)
end

function G.http_fox_request(url, body, method, cookie, x_site)
    local httpc = require("resty.http").new()
    local res, err = nil, nil
    if method == 'POST' then
        res, err = httpc:request_uri(url, {
            method = method,
            body = body or {},
            ssl_verify = false,
            headers = {
                ["Content-Type"] = "application/json",
                ["Cookie"] = cookie or "",
                ["X-Site"] = x_site or ""
            },
        })
    else
        res, err = httpc:request_uri(url, {
            method = method,
            ssl_verify = false,
            headers = {
                ["Cookie"] = cookie or "",
                ["X-Site"] = x_site or ""
            },
        })
    end
    httpc:close();
    if not res then
        debug("http_request error: " .. err)
        ngx.exit(200)
    end

    if res.status ~= 200 and res.status ~= 204 then
        debug("request code errno: " .. url .. "res.status" .. res.status)
        return false
    end

    local ret_data = json.decode(res.body)
    return ret_data
end

--生成请求参数
function G.gen_uri_param(t)
    local param = ""
    for k, v in pairs(t) do
        param = param .. k .. "=" .. v .. "&"
    end
    --delele lasted &
    param = string.sub(param, 1, -2)
    return param
end

function G.append_cookie(new_cookie)
    local existingCookie = ngx.header["Set-Cookie"]
    table.insert(existingCookie, new_cookie)
    ngx.header["Set-Cookie"] = existingCookie
end

return G

